package T03_翱翔BaseDaoUtils;

import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
/**
 * @author lucky monkey
 * @version 1.0
 * @date 2022-05-26 11:45
 */
public class BaseUtil01 {

    private final static String driver="com.mysql.jdbc.Driver";
    private final String url="jdbc:mysql://localhost:3306/MySchool";
    private final String user="roowt";
    private final String pwd="1228";

    static{
        try {
            Class.forName(driver);
        } catch (ClassNotFoundException e) {
            e.printStackTrace();
        }
    }

    public Connection getConn() {
        Connection conn = null;
        try {
            conn = DriverManager.getConnection(url, user, pwd);
        } catch (SQLException e) {
            e.printStackTrace();
        }
        return conn;
    }

    public void CloseAll(Connection conn, Statement stmt, ResultSet rst){
        try {
            if (rst !=null) {
                rst.close();
            }
            if (stmt !=null) {
                stmt.close();
            }
            if (conn !=null) {
                conn.close();
            }
        } catch (SQLException e) {
            e.printStackTrace();
        }
    }

    public boolean update(String sql,Object[] os){
        Connection conn=getConn();
        PreparedStatement pstmt=null;
        int row=0;
        try {
            pstmt=conn.prepareStatement(sql);
            if (os !=null) {
                for (int i = 0; i < os.length; i++) {
                    pstmt.setObject((i+1), os[i]);
                }
            }
            row=pstmt.executeUpdate();
        } catch (SQLException e) {
            e.printStackTrace();
        }finally{
            CloseAll(conn, pstmt, null);
        }
        return row>0;
    }

    public ResultSet query(String sql, Object[] os){
        Connection conn=getConn();
        PreparedStatement pstmt=null;
        ResultSet rst=null;
        try {
            pstmt=conn.prepareStatement(sql);
            if (os !=null) {
                for (int i = 0; i < os.length; i++) {
                    pstmt.setObject((i+1), os[i]);
                }
            }
            rst=pstmt.executeQuery();
        } catch (SQLException e) {
            e.printStackTrace();
        }
        return rst;
    }
}

